import { Select } from "antd";
import { ComponentProps } from "react";
import { RawType } from "../types";

//获取到组件的props属性类型
type SelectProps = ComponentProps<typeof Select>;
interface IdSelectProps extends Omit<SelectProps, "value" | "onChange"> {
  value?: RawType | null | undefined;
  onChange?: (value?: number) => void;
  defaultName?: string; //默认显示名字
  options?: { name: string; id: number }[]; //选项
}

//转化为数字
const toNumber = (num: unknown) => (isNaN(Number(num)) ? 0 : Number(num));

/**
 * @description: Id选择框组件（选项为number类型的）
 * - value可以传入多种类型的值
 * - onChange只会回调number|undefined类型
 * - 当isNaN(Number(value))为true的时候，代表选择默认类型
 * - 当选择默认类型的时候，onChange会回调undefined
 */
export const IdSelect = ({
  defaultName = "负责人",
  ...props
}: IdSelectProps) => {
  const { value, onChange, options, ...resetProps } = props;
  return (
    <Select
      value={options?.length ? toNumber(value) : 0}
      onChange={(value) => onChange?.(toNumber(value) || undefined)}
      {...resetProps}
    >
      {defaultName ? (
        <Select.Option value={0}>{defaultName}</Select.Option>
      ) : null}
      {options?.map((option) => {
        return (
          <Select.Option value={option.id} key={option.id}>
            {option.name}
          </Select.Option>
        );
      })}
    </Select>
  );
};
